<template>
	<div class="tiankong">
		<div class="question">
			<div class="title">
				<span>{{ questIndex }}.填空题
					<span v-if="judgeAnswerType() === 'audio'">
								（语音填空）
					</span>
					<span v-if="judgeAnswerType() === 'picture'">
						（图片填空）
					</span>
					<span v-if="judgeAnswerType() === 'writer'">
						（写字题）
					</span>
				</span>
			</div>
			<div class="question">
				<template v-for="(item,index) in question.quest.question[0].value" :key="index" class="desc">
					<p v-if="item !==''" class="bigDesc" dir="auto">
						{{ item }}
					</p>
				</template>

					<template v-for="(item,index) in question.quest.subQuestion[0].question">
						<div class="resourceDesc">
							<template v-if="item.type ==='audio'">
								<div class="iconBox">
									<img src="@/assets/audio.png" @click="handlePlay(item.value)">
								</div>
							</template>
							<template v-else-if="item.type==='picture'">
								<div class="iconBox">
									<el-image
										style="width: 150px; height: 150px"
										:src="item.value"
										fit="contain"
										:preview-src-list="[String(item.value)]"
										:initial-index="0"
										@click.stop
									/>
								</div>
							</template>
							<template v-else-if="item.type==='video'">
								<div class="iconBox">
									<video controls width="250">
										<source :src="item.value" type="video/webm"/>
									</video>
								</div>
							</template>
						</div>
						<template v-if="item.type==='text'" >
							<div class="text" style="margin-top: 20px;">
								<p v-for="(item1,index1) in litterDesc" :key="index1">
									<span v-for="(item2,index2) in item1" :key="index2">
										<span v-if="item2 !=='^'">
											{{ item2 }}
										</span>
										<span v-else>
											<span class="answer" v-if="judgeAnswerType() === 'text'">
												<el-input
													v-model="state.radio1[(index1+1)*3+(index2+1)*7]"
													placeholder="点击输入"
													clearable
													@change="saveTextAnswer((index1+1)*3+(index2+1)*7)"
												/>
											</span>
											<span class="answerIcon" v-if="judgeAnswerType() === 'audio'">
												<span @click="openDialog('audio',Number(index1))">
													<el-icon><Microphone/></el-icon>
												</span>
												<span class="audioAnswer" v-if="state.answer[index1]"
												      @click.stop="handlePlay(state.answer[index1])">
													<el-icon><Headset/></el-icon>
												</span>
											</span>
											<span class="answerIcon" v-if="judgeAnswerType() === 'picture'">
												<span @click="openDialog('picture',Number(index1))">
													<el-icon><PictureFilled/></el-icon>
												</span>
												<span v-if="state.answer[index1]">
													 <el-image
														 style="width: 150px; height: 150px"
														 :src="state.answer[index1]"
														 fit="contain"
														 :preview-src-list="[state.answer[index1]]"
														 :initial-index="0"
														 @click.stop
													 />
												</span>
											</span>
											<span class="answerIcon" v-if="judgeAnswerType() === 'writer'">
											<span @click="openDialog('writer',Number((index1+1)*10+(index2+1)*5))">
												<el-icon><Edit/></el-icon>
											</span>
											<span v-if="state.answer[(index1+1)*10+(index2+1)*5]">
												<el-image
													style="width: 50px; height: 50px"
													:src="state.answer[(index1+1)*10+(index2+1)*5].src"
													:preview-src-list="[String(state.answer[(index1+1)*10+(index2+1)*5].src)]"
													:initial-index="0"
													fit="contain"
												/>
											</span>
										</span>
										</span>
									</span>
								</p>
							</div>
						</template>
					</template>
			</div>
		</div>
		<el-dialog
			v-model="state.dialogVisible"
			title="题目作答"
			width="500"
			draggable
			destroy-on-close
			@close="setUserAnswer()"
		>
			<div v-if="state.dialogType === 'audio'">
				<Recoder :questionIndex="seq" :answerIndex="state.answerIndex"></Recoder>
			</div>
			<div v-if="state.dialogType === 'picture'">
				<image-uploader :questionIndex="seq" :answerIndex="state.answerIndex"></image-uploader>
			</div>
			<div v-if="state.dialogType === 'writer'">
				<XieZi
					:writedStroks="[]"
					@saveWritedChar="saveWritedChar"
				>
				</XieZi>
			</div>

			<template #footer>
				<div class="dialog-footer" v-if="state.dialogType!=='writer'">
					<el-button @click="state.dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="setUserAnswer()">
						确定
					</el-button>
				</div>
			</template>
		</el-dialog>

	</div>
</template>
<script setup lang="ts">

import {toRefs, defineProps, reactive, onMounted, ref, PropType, Ref} from 'vue'
import {Microphone, PictureFilled, Edit, Headset, Service} from "eleicon";
import {useDataStore} from "@/stores/useDataStore";
import Recoder from "@/components/Recoder/Recoder.vue";
import Bus from "@/utils/bus";
import ImageUploader from "@/components/imageUploader/imageUploader.vue";
import XieZi from "@/components/questionType/XieZi/XieZi.vue";


const props = defineProps({
	//子组件接收父组件传递过来的值
	question: {
		type: Object as PropType<{
			quest: {
				subQuestion: Array<any>,
				question: Array<any>
			},
			seqNum: number
		}>,
	},
	questIndex: {
		type: Number
	},
	seq: {
		type: Number
	}
})

const {question, questIndex,seq} = toRefs(props) as {
	question: Ref<{
		quest: {
			subQuestion: Array<any>,
			question: Array<any>
		},
		seqNum: number
	}>,
	questIndex: Ref<number>,
	seq: Ref<number>
}


const userAnswerState = useDataStore();

type stateType = {
	radio1: string[],
	dialogVisible: boolean,
	dialogType: string
	answerIndex: number,
	answer: any[],
	answer1: any[],
	fileList: any[],
}
const state = reactive<stateType>({
	radio1: [],
	dialogVisible: false,
	dialogType: '',
	answerIndex: 0,      // 第几个空的答案,
	answer: [],
	answer1: [],
	fileList: [],
})
onMounted(() => {
	Bus.on('uploadAudio' + seq.value, (data: any) => {
		state.answer[data.index] = data.answer
	})
	Bus.on('uploadPicture' + seq.value, (data: any) => {
		state.answer[data.index] = data.answer
	})
	question.value.quest.subQuestion[0].question.push(question.value.quest.subQuestion[0].question.shift())
})

const litterDesc = question?.value?.quest.subQuestion[0].question[0].value.map((item: string, index: any) => {
	//
	return item.replace(/（.*?）|\(.*?\)/g, '^').split('');
});

const judgeAnswerType = (): string => {
	return question?.value?.quest.subQuestion[0].content.value[0][0];
}


const handlePlay = (source: string) => {
	setUserAnswer();
	if (userAnswerState.currentAudio) {
		userAnswerState.currentAudio.pause(); // 暂停当前音频
		userAnswerState.currentAudio = null; // 释放当前音频
	}

	userAnswerState.currentAudio = new Audio(source) as any; // 创建新的 Audio 对象
	userAnswerState.currentAudio?.play(); // 播放音频
}


const setUserAnswer = () => {
	state.dialogVisible = false
	const type = judgeAnswerType();
	// 根据不同的答案类型更改answer的结构
	state.answer1 = state.answer.map((item: any) => {
		if (type == 'audio') {
			return {
				audios: [getRealUrl(item)]
			}
		} else if (type == 'picture') {
			return {
				pics: [getRealUrl(item)]
			}
		} else if (type == 'writer') {
			// item.src = ''
			return {
				writer: [{
					src: '',
					strokes: item.strokes
				}]
			}
		} else if (type == 'text') {
			return {
				text: item
			}
		}
	})
	// 答案去掉空白
	let answer: Array<any> = [];
	state.answer1.forEach((item, index) => {
		if (item) {
			answer.push(item)
		}
	})
	const payload = {
		template: question?.value?.quest.subQuestion[0].template,
		userAnswer: answer
	};
	userAnswerState.setUserAnswer(payload, seq.value-1);
	console.log(userAnswerState.userAnswer)
}

const openDialog = (type: string, index1: number) => {
	state.dialogType = type;
	state.answerIndex = index1;
	state.dialogVisible = true;
}

const saveWritedChar = (val: {
	imageUrl: string,
	strokes: any
}) => {
	const answer: {
		src: string,
		strokes: []
	} = {
		src: '',
		strokes: []
	}
	answer.src = val.imageUrl;
	answer.strokes = val.strokes;
	state.answer[state.answerIndex] = answer;
	state.dialogVisible = false;
}

const saveTextAnswer = (index: number) => {
	state.answer[index] = state.radio1[index];
	setUserAnswer();
}

const getRealUrl = (url: string) => {
	return url.split('/')[url.split('/').length - 2] + '/' + url.split('/')[url.split('/').length - 1];
}


</script>
<style scoped lang="scss">
.tiankong {
	img {
		width: 30px;
		height: 30px;
		object-fit: contain;
	}
	:deep(.el-image) {
		//margin-left: -50px;

		text-indent: 0;
	}

	:deep(.el-input) {
		width: fit-content;
	}

	:deep(.el-input__wrapper) {

		border-radius: 0;
		border: 0 solid black;
		border-bottom-width: 2px;
		box-shadow: 0 0 0 0 transparent;
		/*outline: medium;*/
	}

	.question {
		margin-bottom: 20px;

		.title {
			font-size: 20px;
			font-weight: 500;
			margin-bottom: 10px;
			color: #6a727f;
		}

		.dot {
			font-weight: 700;
			color: #5189dd;
			margin-right: 5px;
		}

		.question {
			font-size: 19px;
			color: #7c7787;
			text-indent: 2em;
			.resourceDesc {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				.iconBox {
					display: flex;
					justify-content: center;
					align-items: center;
					font-size: 30px;
					margin-top: 20px;
				}
			}

			.underline {
				font-size: 15px;
				text-indent: 0;
				display: inline-block;
				text-align: center;
				color: #aeb1b8;
				padding: 5px;
				border-bottom: 2px solid black;
			}

			.bigDesc {
				margin-bottom: 20px;
				font-weight: 500;
				font-size: 18px;
			}

			.answerIcon {
				font-size: 30px;
				border-bottom: 2px solid black;

				.audioAnswer {
					display: inline-block;
					margin-left: 20px;
				}

				.text {
					font-size: 15px;
				}
			}
		}

	}
}

</style>